<?php
/**
 * Descript 微信小程序token类
 * User: blue
 * Date: 2018/8/5 12:12
 */

namespace app\api\server;


use app\api\model\WxUser;
use app\lib\enum\ScopeEnum;
use app\lib\exception\TokenException;
use app\lib\serverLib\Curl;
use think\Exception;

class WxToken extends BaseToken
{
    private $appid;
    private $appSecret;
    private $baseUrl;
    public function __construct()
    {
        $this->appid=config('wx.app_id');
        $this->appSecret=config('wx.app_secret');
        $this->baseUrl=config('wx.openIdUrl');
    }

    /**
     * 微信获取token
     * 获取微信openid->数据库返回openid对应的主键没有则新增
     * ->组合特定格式存入缓存->返回token
     * @param string $code 微信登录code
     */
    public function getToken($code=""){
        $this->url=sprintf($this->baseUrl,$this->appid,$this->appSecret,$code);
        //获取openid
        $wxResultArr=$this->getOpenid();
        //数据库操作,如数据库中有openid,则直接返回uid,否则新增数据,返回uid
        $data=WxUser::get('openid',$wxResultArr['openid']);
        if($data){
            $uid=$data->id;
        }else{
            $user=WxUser::create([
                'openid'=>$wxResultArr['openid']
            ]);
            $uid=$user->id;
        }
        $wxResultArr['uid']=$uid;
        $wxResultArr['scope']=ScopeEnum::USER;
        $token=$this->productToken();
        $expire=config('wx.token_expire');
        //写入缓存中
        cache($token,josn($wxResultArr),$expire);
        return $token;
    }

    /**
     * 获取openid 方法
     * @return mixed
     * @throws TokenException
     */
    private function getOpenid(){
        $openid=(new Curl())->curlRequest($this->url);
        //根据微信的返回值,判断是否成功
        $result=json_decode($openid,true);
        if(isset($result['errcode'])){throw new TokenException(['message'=>$result['errmsg']]);}
        //这里直接返回数组
        return $result;
    }
}